package com.example.test.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.geotools.data.postgis.WKBReader;
import org.geotools.geojson.geom.GeometryJSON;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.postgis.PGgeometry;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({String.class})
public class GeometryTypeHandler extends BaseTypeHandler<String> {
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
//		PGgeometry pGgeometry = new PGgeometry(parameter);
//		ps.setObject(i, pGgeometry);
	}

	@Override
	public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
		if (!columnName.equals("geometry")) return rs.getString(columnName);
		String wkbString = rs.getString(columnName);
		if (wkbString == null) {
			return null;
		}
		WKBReader wkbReader = new WKBReader();
		byte[] bytes = WKBReader.hexToBytes(wkbString);
		Geometry readGeometry =null;
		try {
			readGeometry = wkbReader.read(bytes);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		GeometryJSON geometryJSON = new GeometryJSON(7);
		return geometryJSON.toString(readGeometry);
	}

	@Override
	public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		PGgeometry pGgeometry = new PGgeometry(rs.getString(columnIndex));
		if (pGgeometry == null) {
			return null;
		}
		return pGgeometry.toString();
	}

	@Override
	public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {

		PGgeometry pGgeometry = new PGgeometry(cs.getString(columnIndex));
		if (pGgeometry == null) {
			return null;
		}
		return pGgeometry.toString();
	}
}
